package com.freeager.springboot.atomikos.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Random;

@Controller
@RequestMapping("/test")
public class TestController {

	@Autowired
	private JdbcTemplate jdbcTemplate1;

	@Autowired
	private JdbcTemplate jdbcTemplate2;

	@Transactional
	@RequestMapping("")
	@ResponseBody
	public String test() {
		//第一个数据采用随机数，保证第二次能执行
		jdbcTemplate1.execute("insert into test_1(id) values("+new Random().nextInt(10000) +")");
		//第二条插入语句第二次执行时将报错，回滚
		jdbcTemplate2.execute("insert into test_2(id) values(20)");
		return "test ok...";
	}
}
